package net.lab1024.sa.base.module.support.rule.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.lab1024.sa.base.module.support.rule.dao.RuleCepStepDao;
import net.lab1024.sa.base.module.support.rule.domain.entity.RuleCepStep;
import net.lab1024.sa.base.module.support.rule.service.RuleCepStepService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 规则步骤 Service 实现类
 */
@Service
public class RuleCepStepServiceImpl extends ServiceImpl<RuleCepStepDao, RuleCepStep> implements RuleCepStepService {

    @Autowired
    private RuleCepStepDao ruleCepStepDao;


    @Override
    public boolean save(RuleCepStep ruleCepStep) {
        ruleCepStep.setCreatedTime(LocalDateTime.now());
        ruleCepStep.setUpdatedTime(LocalDateTime.now());
        return super.save(ruleCepStep);
    }

    @Override
    public boolean update(RuleCepStep ruleCepStep) {
        ruleCepStep.setUpdatedTime(LocalDateTime.now());

        return super.updateById(ruleCepStep);
    }

    @Override
    public boolean deleteById(Long id) {
        return super.removeById(id);
    }

    @Override
    public boolean deleteByRuleId(Long id) {
        int i = ruleCepStepDao.deleteByRuleId(id);
        if(i > 0){
            return true;
        }
        return false;
    }

    @Override
    public RuleCepStep getById(Long id) {
        return super.getById(id);
    }

    @Override
    public List<RuleCepStep> getByRuleId(Long ruleId) {
        return ruleCepStepDao.selectByRuleId(ruleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchSave(Long ruleId, List<RuleCepStep> steps) {
        // 先删除原有的步骤
        ruleCepStepDao.deleteByRuleId(ruleId);
        
        if (steps == null || steps.isEmpty()) {
            return true;
        }

        // 设置步骤的基本信息
        LocalDateTime now = LocalDateTime.now();
        for (int i = 0; i < steps.size(); i++) {
            RuleCepStep step = steps.get(i);
            step.setRuleId(ruleId);
            step.setStepOrder(i + 1);
            step.setCreatedTime(now);
            step.setUpdatedTime(now);
        }

        // 批量插入新的步骤
        return ruleCepStepDao.batchInsert(steps) > 0;
    }
} 